package com.lipaluma.test.util;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class XmlUtil {
	public static final String XMLNS = "xmlns=\"http://www.lipaluma.com/data-parser/xml\"";
	
	
	public static <T> T parse(Class<T> target, String xml) throws Exception {
		String node = xml.substring(xml.indexOf("<"), xml.indexOf(">")+1);
		if(!node.contains(XMLNS)) {
			if(node.contains(" "))
				xml = new StringBuilder(xml.substring(0, xml.indexOf(" "))).append(" ").append(XMLNS).append(xml.substring(xml.indexOf(" "))).toString();
			else if(node.contains("/"))
				xml = new StringBuilder(xml.substring(0, xml.indexOf("/"))).append(" ").append(XMLNS).append(xml.substring(xml.indexOf("/"))).toString();
			else
				xml = new StringBuilder(xml.substring(0, xml.indexOf(">"))).append(" ").append(XMLNS).append(xml.substring(xml.indexOf(">"))).toString();
		}
			
		JAXBContext context = JAXBContext.newInstance(target);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		return target.cast(unmarshaller.unmarshal(new StringReader(xml)));
	}
	
}
